package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"ucenter/app/service"
	"ucenter/app/validator"
)

func PreOrder(c *gin.Context) {
	var (
		uid        = c.GetInt64("UID")
		orderVtr   = validator.OrderValidator{}
		returnData = map[string]interface{}{}
	)
	if uid == 0 {
		return
	}
	if err := c.ShouldBind(&orderVtr); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if vs, msg := orderVtr.Valid(); !vs {
		c.JSON(http.StatusBadRequest, gin.H{"error": msg})
		return
	}
	_, userInfo, _ := service.GetUserService().GetUserBaseInfo(uid)
	if userInfo.Phone == "" {
		returnData["code"] = 402
		returnData["error"] = "PHONE_NEEDED"
		c.JSON(400, returnData)
		return
	}
	if userInfo.Email == "" {
		returnData["code"] = 402
		returnData["error"] = "EMAIL_NEEDED"
		c.JSON(400, returnData)
		return
	}
	token, err := service.Svc.PreOrder(uid, orderVtr.Channel, "", service.In, orderVtr.Amount, orderVtr.AppId)
	if err != nil {
		switch err.(type) {
		case *service.PayError:
			returnData["code"] = err.(*service.PayError).Code
			returnData["error"] = err.(*service.PayError).Error()
		default:
			returnData["code"] = 500
			returnData["error"] = err.Error()
		}
		c.JSON(400, returnData)
		return
	}
	_, user, _ := service.GetUserService().GetUserBaseInfo(uid)
	returnData["code"] = 200
	returnData["data"] = map[string]interface{}{
		"token": token.Payload,
		"payload": map[string]interface{}{
			"appId": "",
			"orderId": token.AppOrderId,
			"orderAmount": orderVtr.Amount,
			"customerName": user.Name,
			"customerPhone": user.Phone,
			"customerEmail": user.Email,
		},
	}
	c.JSON(200, returnData)
	return
}

//支付网关回调处理
func PayNotify(c *gin.Context) {
	var (
		orderId int64
		err     error
	)
	notifyRawData, err := c.GetRawData()
	if err != nil {
		c.JSON(400, "request body empty!")
		return
	}

	body := &service.PayNotifyBody{}
	if err := json.Unmarshal(notifyRawData, body); err != nil {
		c.JSON(400, fmt.Sprintf("request body unmarshal fail, %s", err.Error()))
		return
	}
	var status string
	// 0支付中 1支付成功 2支付失败 3支付取消
	//'Success','Fail','InProgress','UnConfirmed','Unknown'
	switch body.Status {
	case 0:
		status = "InProgress"
		return
	case 1:
		status = "Success"
	case 2:
		status = "Fail"
	case 3:
		status = "UnConfirmed"

	}
	orderId, err = strconv.ParseInt(body.OrderId, 10, 64)
	if err != nil {
		c.JSON(400, fmt.Sprintf("request app_order_id get fail %s", err.Error()))
		return
	}
	err = service.Svc.UpdateOrderStatus(orderId, status)
	if err != nil {
		c.JSON(400, fmt.Sprintf("update order fail %s", err.Error()))
		return
	}
	c.JSON(200, "SUCCESS")
	return
}
